import axios from 'axios';
import React from 'react';

class Get extends React.Component {
  state = {
    data: [],
    component: this.props.loading || ''
  };

  async componentDidMount() {
    // console.log(this.props);
    //{url: 'http://localhost:8080/getStudents', loading: {…}, error: {…}, children: ƒ}

    const { url, delay, children, loading, error } = this.props;

    //有可能存在错误的情况
    try {
      const result = await axios(url);
      // console.log(result);

      this.setState(
        {
          data: result.data
        },
        () => {
          //1秒后修改props.children内容
          setTimeout(() => {
            this.setState({
              component: children(this.state.data)
            });

            // console.log(this.state.component);
            /**
             * [
             *   {$$typeof: Symbol(react.element), type: 'tr', key: '1', ref: null, props: {…}, …},
             *   {$$typeof: Symbol(react.element), type: 'tr', key: '1', ref: null, props: {…}, …},
             *   {$$typeof: Symbol(react.element), type: 'tr', key: '1', ref: null, props: {…}, …},
             *   {$$typeof: Symbol(react.element), type: 'tr', key: '1', ref: null, props: {…}, …},
             *   {$$typeof: Symbol(react.element), type: 'tr', key: '1', ref: null, props: {…}, …},
             *   {$$typeof: Symbol(react.element), type: 'tr', key: '1', ref: null, props: {…}, …},
             *   {$$typeof: Symbol(react.element), type: 'tr', key: '1', ref: null, props: {…}, …}
             * ]
             */
          }, delay || 0);
        }
      );
    } catch (e) {
      this.setState({
        component: error || 'Error'
      });

      throw e;
    }
  }

  render() {
    //返回一个React元素组件集合
    return this.state.component;
  }
}

export default Get;
